﻿namespace LookupWithPicker
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using Microsoft.SharePoint.WebControls;
    using Microsoft.SharePoint;

    public class CustomLookupEntityEditor : EntityEditorWithPicker 
    {
        public CustomLookupEntityEditor()
        {
        }

        protected override bool DefaultPlaceButtonsUnderEntityEditor
        {
            get
            {
                return this.MultiSelect;
            }
        }

        protected override int DefaultRows
        {
            get
            {
                if (!this.MultiSelect)
                {
                    return base.DefaultRows;
                }

                return 3;
            }
        }

        public PickerEntity GetEntityById(int id)
        {
            PickerEntity res = null;
            if (id > 0)
            {
                using (SPWeb web = SPContext.Current.Site.OpenWeb(this.GetWebId()))
                {
                    SPList list = web.Lists[this.GetListId()];
                    SPQuery query1 = new SPQuery();
                    query1.Query = string.Format("<Where><Eq><FieldRef Name=\"ID\"/><Value Type=\"Integer\">{0}</Value></Eq></Where>", id);
                    SPListItemCollection items = list.GetItems(query1);
                    if (items.Count > 0)
                    {
                        res = this.GetEntity(items[0]);
                    }
                }
            }

            return res;
        }

        protected override PickerEntity[] ResolveErrorBySearch(string unresolvedText)
        {
            List<PickerEntity> res = new List<PickerEntity>();
            using(SPWeb web = SPContext.Current.Site.OpenWeb(this.GetWebId())) {
                SPList list = web.Lists[this.GetListId()];
                SPQuery query = new SPQuery();
                query.Query = string.Format("<Where><BeginsWith><FieldRef Name=\"{0}\"/><Value Type=\"Text\">{1}</Value></BeginsWith></Where>", this.GetFieldName(), unresolvedText);
                SPListItemCollection items = list.GetItems(query);
                foreach (SPListItem item in items)
                {
                    res.Add(this.GetEntity(item));
                }

                return res.ToArray();
            }
        }

        public override PickerEntity ValidateEntity(PickerEntity needsValidation)
        {
            PickerEntity res = needsValidation;

            if (!string.IsNullOrEmpty(needsValidation.DisplayText))
            {
                using (SPWeb web = SPContext.Current.Site.OpenWeb(this.GetWebId()))
                {
                    SPList list = web.Lists[this.GetListId()];
                    SPListItemCollection items;

                    SPQuery query2 = new SPQuery();
                    query2.Query = string.Format("<Where><Eq><FieldRef Name=\"{0}\"/><Value Type=\"Text\">{1}</Value></Eq></Where>", this.GetFieldName(), needsValidation.DisplayText);
                    items = list.GetItems(query2);
                    if (items.Count > 0)
                    {
                        res = this.GetEntity(items[0]);
                    }
                    else
                    {
                        SPQuery query1 = new SPQuery();
                        query1.Query = string.Format("<Where><Eq><FieldRef Name=\"ID\"/><Value Type=\"Integer\">{0}</Value></Eq></Where>", needsValidation.Key);
                        items = list.GetItems(query1);
                        if (items.Count > 0)
                        {
                            res = this.GetEntity(items[0]);
                        }
                    }
                }
            }
            return res;
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.PickerDialogType = typeof(CustomLookupPickerDialog);
        }

        private Guid GetListId()
        {
            string listId = this.CustomProperty.Split(new char[] { '#' })[0];
            return new Guid(listId);
        }

        private string GetFieldName()
        {
            string fieldName = this.CustomProperty.Split(new char[] { '#' })[1];
            return fieldName;
        }

        private Guid GetWebId()
        {
            string webId = this.CustomProperty.Split(new char[] { '#' })[2];
            return new Guid(webId);
        }

        private PickerEntity GetEntity(SPListItem item)
        {
            PickerEntity entity = new PickerEntity();
            string val = SPFieldLookupWithPicker.GetFieldValue(item, this.GetFieldName());
            entity.DisplayText = val;
            entity.Key = "" + item["ID"];
            entity.Description = item["ID"] + ". " + val;
            entity.IsResolved = true;
            return entity;
        }
    }
}
